package com.os.opencv.java.chapter12;

import org.opencv.core.Core;
import org.opencv.core.CvType;
import org.opencv.core.Mat;
import org.opencv.ml.KNearest;

import static org.opencv.ml.Ml.ROW_SAMPLE;

public class Knn {

    public static void main(String[] args) {
        System.loadLibrary(Core.NATIVE_LIBRARY_NAME);

        //训练数据，每组两个数据，分别表示身高和体重
        float[] trainData = {180,81,178,75,185,87,168,65,
        173,68,160,52,158,55,170,63,163,60,168,66};
        Mat trainMat = new Mat(10,2, CvType.CV_32FC1);
        trainMat.put(0,0,trainData);

        //训练标签数据，0为男性，1为女性
        float[] label = {0,0,0,0,0,1,1,1,1,1};
        Mat labelMat = new Mat(10,1,CvType.CV_32FC1);
        labelMat.put(0,0,label);

        //测试数据
        float[] testData = {185,79,159,52};
        Mat testMat = new Mat(2,2,CvType.CV_32FC1);
        testMat.put(0,0,testData);

        //创建knearest类对象
        KNearest knn = KNearest.create();

        //用训练数据进行训练并输出训练结果
        boolean result = knn.train(trainMat, ROW_SAMPLE, labelMat);

        if(result){
            System.out.println("training successed!");
        }else{
            System.out.println("training failed!");
        }

        System.out.println();

        //寻找k近邻
        int k=5;
        Mat results = new Mat();
        Mat responses = new Mat();
        Mat dist = new Mat();
        knn.findNearest(testMat, k, results, responses, dist);

        //输出结果数据
        System.out.println("results:\n" + results.dump());
        System.out.println();
        System.out.println("neighborResponses:\n" + responses.dump());
        System.out.println();
        System.out.println("distance:\n" + dist.dump());
        System.out.println();

        //用文字输出判断结果
        for(int i=0; i<results.height(); i++){
            if(results.get(i,0)[0] == 0){
                System.out.println("no." + i + " is male");
            }else{
                System.out.println("no." + i + " is female");
            }
        }
    }
}
